import axios, { type Method } from 'axios';
import { useUserStore } from '@/stores'
import router from '@/router';
import { showFailToast } from 'vant'

const instance = axios.create({
  baseURL: 'https://consult-api.itheima.net/',
  timeout:8000
})

instance.interceptors.request.use(
  config => {
    const userStore = useUserStore()
    if (userStore.user?.token) {
      config.headers.Authorization = `Bearer ${userStore.user.token}` 
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

instance.interceptors.response.use(
  response => {
    // 如果 code 不等于 10000， 就出错了
    if (response.data.code !== 10000) {
      showFailToast(response.data.message || '出错啦~~~')
      return Promise.reject(response.data)
    }
    return response.data
  },
  err => {
    if (err.response.status === 401) {
      const userStore = useUserStore()
      userStore.delUser()
      router.push('/login')
    }
    return Promise.reject(err)
  }
)

type Data<T> = {
  code: number,
  message: string,
  data: T
}

// 请求参数
const request = <T>(url:string, method:Method = 'get', submitData?:object) => {
  return instance.request<T,Data<T>>({
    url,
    method,
    [ method.toLowerCase() === 'get' ? 'params' : 'data']:submitData
  })
}

export { instance, request }